﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace Connect_socket_helper
{
    static class SocketMessageHelper
    {
        public static IPAddress host = Dns.GetHostEntry("www.actiongeo.top").AddressList[0];
        public static int port = 18088;
        public static void sendMessageByDic(Dictionary<string, string> dic)
        {
            TcpClient client = new TcpClient();
            client.Connect(host, port);

            NetworkStream clientStream = client.GetStream();
            byte[] requestBuffer = Encoding.ASCII.GetBytes(dic2jsonStr(dic));
            clientStream.Write(requestBuffer, 0, requestBuffer.Length);

            //Console.WriteLine(waitBack(client));
            clientStream.Close();
            client.Close();
            Console.ReadKey();
        }

        static string dic2jsonStr(Dictionary<string, string> dic)
        {
            string res = "{";
            foreach (KeyValuePair<string, string> item in dic)
            {
                res += $"\"{item.Key}\":\"{item.Value}\",";
            }
            res = res.Substring(0, res.Length - 1) + "}";
            return res;
        }

        static string waitBack(TcpClient client)
        {
            NetworkStream clientStream = client.GetStream();
            //read response  
            byte[] responseBuffer = new byte[1024];
            MemoryStream memStream = new MemoryStream();
            int bytesRead = 0;
            do
            {
                bytesRead = clientStream.Read(responseBuffer, 0, 1024);
                memStream.Write(responseBuffer, 0, bytesRead);

            } while (bytesRead > 0);

            byte[] buffer = memStream.GetBuffer();
            return Encoding.ASCII.GetString(buffer);
        }
    }
}
